﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security.Principal;
namespace Intranet
{
    public class IntranetController : Controller
    {
        protected virtual Guid createUser(IIdentity identity)
        {
            using (Models.intranetDBEntities entities = new Models.intranetDBEntities())
            {
                Models.user user = new Models.user();
                user.firstName = identity.Name;
                user.lastName = identity.Name;
                user.logonName = identity.Name;
                user.userId = Guid.NewGuid();
                entities.users.AddObject(user);
                entities.SaveChanges();
                return user.userId;
            }
                        
        }
        public virtual Guid RegisterOrAuthenticateUser(IIdentity identity)
        {
            if (identity.IsAuthenticated)
            {
                using (Models.intranetDBEntities entities = new Models.intranetDBEntities())
                {
                    if (entities.users.Any(p => p.logonName == identity.Name))
                    {
                        return entities.users.First(p => p.logonName == identity.Name).userId;
                    }
                    else
                    {
                        // create user
                        return createUser(identity);
                    }
                }
            }
            else
            {
                return createUser(identity);
            }
        }

        public ActionResult CustomError(string message)
        {
            return View("CustomError", message);
        }
    }
}